<template>
  <div class="app_content">
      <el-form :inline="true" ref="queryForm" :model="queryParams" class="demo-form-inline" :size="size" v-if="showSearch">
        <el-form-item label="用户名称">
      <el-input v-model="queryParams.userName" clearable placeholder="用户名称" style="width: 240px"/>
      </el-form-item>
      <el-form-item label="电话号码">
      <el-input v-model="queryParams.phonenumber" clearable placeholder="电话号码" style="width: 240px"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="querySubmit">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-search'"/>
          搜索</el-button>
        <el-button   @click="resetSubmit">
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-redo'"/>
          重置</el-button>
      </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            :size="size"
            @click="handleAdd"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-add-one'"/>
          添加用户</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            :size="size"
            :disabled="multiple"
            @click="cancelAuthUserAll"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-delete-five'"/>
          批量取消授权</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            :size="size"
            @click="handleClose"
          >
          <component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-return'"/>
          返回</el-button>
        </el-col>
        <!-- <el-col :span="1.5">
          <Export  :dc="true"  :dr="true" :exlData="tableData" :tHead="staticData.ExportHead" :tName="'导出的标题'" ></Export>
        </el-col>
  -->
        <!-- <RightToolbar :showSearch="showSearch" @queryTable="getList" :columns="columns"/> -->
        <RightToolbar :showSearch="showSearch" @queryTable='getList' @showSearchClick='showSearchClick' :columns="columns"/>
      </el-row>
      <el-table v-loading="loading" :data="tableData" :height="maxHeight"  style="width: 100%" @selection-change="handleSelectionChange"  :size="size"
      >
      <el-table-column type="selection" width="55" />
      <el-table-column label="编号" prop="id" show-overflow-tooltip key="id" v-if="columns[0].visible">
        <template #default="scope">{{scope.$index+1}}</template>
        </el-table-column>
      <el-table-column label="用户名称" prop="userName" :show-overflow-tooltip="true" key="userName"  v-if="columns[1].visible"/>
      <el-table-column label="用户昵称" prop="nickName" :show-overflow-tooltip="true" key="nickName"  v-if="columns[2].visible"/>
      <el-table-column label="邮箱" prop="email" :show-overflow-tooltip="true" key="email"  v-if="columns[3].visible"/>
      <el-table-column label="手机" prop="phonenumber" :show-overflow-tooltip="true" key="phonenumber"  v-if="columns[4].visible"/>
      <el-table-column label="状态" prop="status" :formatter="statusFormat" show-overflow-tooltip key="status"  v-if="columns[5].visible">
        </el-table-column>
      <el-table-column label="创建时间" prop="createTime" show-overflow-tooltip key="createTime"  v-if="columns[6].visible"/>
      <el-table-column label="操作" fixed="right" align="center"  >
      <template #default="scope">
          <el-button :size="size" type="danger"  text @click="handleCloseAuth(scope.row)"
          ><component :theme="iconTheme" :size="iconSize" :strokeWidth="iconStrokeWidth" :is="'icon-delete-five'"/>取消授权</el-button
          >
          
      </template>
      </el-table-column>
  </el-table>
  <div style="margin-top:10px;position: absolute;right: 0;margin-right:20px">
      <el-pagination
        v-model:currentPage="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :small="small"
        :disabled="disabled"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
  </div>
  <select-user ref="selectRef" :roleId="queryParams.roleId" @ok="querySubmit" />
  </div>
  
</template>

<script  >
import RightToolbar from '@/components/RightToolbar/index.vue';
import { allocatedUserList, authUserCancel, authUserCancelAll } from "@/api/system/role";
import { computed, ref ,reactive,onMounted,getCurrentInstance,toRefs} from 'vue'
import selectUser from "./selectUser.vue";
import { useI18n } from 'vue-i18n';
import { useStore } from 'vuex';
import {useRoute,useRouter} from 'vue-router';
import {
Delete,
Edit,
Plus,
Close
} from '@element-plus/icons-vue'

export default defineComponent({
  components:{
    selectUser
  },
setup(){
  const { proxy } = getCurrentInstance();//关键代码
  const queryForm=ref(null)
  const selectRef=ref(null)
  const { t } = useI18n();
  const store = useStore();
  const route=useRoute()
  const router=useRouter() 
  const staticData=reactive({
    formData:{
      name: '',
      age: '',
    },
    userIds:[],
    maxHeight:store.getters['setting/mode']=='horizontal'?document.body.clientHeight - 265:store.getters['setting/isFullScreen']!=false ?document.body.clientHeight - 360:document.body.clientHeight - 320,
    single:true,
    multiple:true,
    showSearch:true,
    background:false,
    disabled :false,
    search:'',
    tableData:[],
    // 日期范围
    dateRange: [],
    // 菜单状态数据字典
    statusOptions: [],
    // 查询参数
    queryParams: {
      pageNum: 1,
      pageSize: 10,
      roleId: undefined,
      userName: undefined,
      phonenumber: undefined
    },
    total:0,
    loading:true, 
    ExportHead:{
      id: "编号",
      name: "角色名称",
      age: "权限字符",
      xb: "显示顺序",
      des: "状态",
      date: "创建时间",
    },
    // 列信息
    columns: [
      { key: 0, label: `编号`, visible: true },
      { key: 1, label: `用户名称`, visible: true },
      { key: 2, label: `用户昵称`, visible: true },
      { key: 3, label: `邮箱`, visible: true },
      { key: 4, label: `手机`, visible: true },
      { key: 5, label: `状态`, visible: true },
      { key: 6, label: `创建时间`, visible: true },
      
    ],
  })
  const size = computed(() => {
        return store.getters['setting/size'];
  });

  const small =computed(() => {
    return size.value=='small'?true:false
  });
  const visitedRouteList = computed(() => {
        return store.getters['tabsBar/visitedRoutes'];
      });

  const filterTableData = computed(() =>
    staticData.tableData.filter(
      (data) =>
        !staticData.search.value ||
        data.name.toLowerCase().includes(staticData.search.value.toLowerCase())
    )
  )
    onMounted(() => {
      proxy.$getDicts("sys_normal_disable").then(response => {
        staticData.statusOptions = response.data;
      });
      const roleId = route.query.roleId;
      if (roleId) {
        staticData.queryParams.roleId = roleId;
        proxy.getList()
      }
      
    })
    const isActive = (route) => {
        return route.path === router.currentRoute.value.path;
      };
    const toLastTag = (latestView) => {
        
        if (latestView) {
          router.push(latestView);
        } else {
          router.push('/');
        }
      };

      const handleTabRemove = async (data) => {
        let view;
        visitedRouteList.value.forEach((item) => {
          if (data.activePath == item.path) {
            view = item;
          }
        });
        
        const { visitedRoutes } = await store.dispatch('tabsBar/delRoute', view);
        if (isActive(view)) {
          toLastTag(data.tarPath);
        }
      };


  const methods = {
     getList(){
        staticData.loading = true;
        allocatedUserList(staticData.queryParams).then(
          response => {
            staticData.tableData = response.rows;
            staticData.total = response.total;
            staticData.loading = false;
          }
      );
     },
    // 岗位状态字典翻译
    statusFormat(row, column) {
      const data=proxy.$selectDictLabel(staticData.statusOptions, row.status)
      let stateClass
      // if(data=='正常'){
      //   stateClass='status_success'
      // }else{
      //   stateClass='status_error'
      // }
      
      return data;
    },
     /**
      * 显示或隐藏搜索条件
      **/
     showSearchClick(data){
       staticData.showSearch=data
     },
     handleAdd(row){
      selectRef.value.show();
    },
    handleClose(){
      let data={
        activePath:'/system/auth-user',
        tarPath:'/system/role'
      }
      handleTabRemove(data)
      

    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      staticData.userIds = selection.map(item => item.userId)
      staticData.multiple = !selection.length
    },
    /** 取消授权按钮操作 */
    handleCloseAuth(row) {
      const roleId = staticData.queryParams.roleId;
      ElMessageBox.confirm('确认要取消该用户"' + row.userName + '"角色吗？', t('confirm.title'), {
      confirmButtonText: t('btn.confirm'),
      cancelButtonText: t('btn.cancel'),
      dangerouslyUseHTMLString: true,
      type: 'warning',
    })
      .then(function() {
        return authUserCancel({ userId: row.userId, roleId: roleId });
      }).then(() => {
        proxy.getList();
        proxy.Success("取消授权成功");
      }).catch(() => {});
    },
    /** 批量取消授权按钮操作 */
    cancelAuthUserAll(row) {
      const roleId = staticData.queryParams.roleId;
      const userIds = staticData.userIds.join(",");
      ElMessageBox.confirm('是否取消选中用户授权数据项？', t('confirm.title'), {
      confirmButtonText: t('btn.confirm'),
      cancelButtonText: t('btn.cancel'),
      dangerouslyUseHTMLString: true,
      type: 'warning',
    })
      .then(function() {
        return authUserCancelAll({ roleId: roleId, userIds: userIds });
      }).then(() => {
        proxy.getList();
        proxy.Success("取消授权成功");
      }).catch(() => {});
    },
    resetSubmit(){
      staticData.dateRange=[]
      queryForm.value.clearValidate()
      queryForm.value.resetFields();
      proxy.getList()
    },
    querySubmit(){
      staticData.queryParams.pageNum = 1;
      proxy.getList()
    },
    handleSizeChange (val) {
      console.log(`${val} items per page`)
      staticData.queryParams.pageSize =val;
      proxy.getList()
    },
    handleCurrentChange(val){
      console.log(`current page: ${val}`)
      staticData.queryParams.pageNum =val;
      proxy.getList()
    }
   }
    return {
      Delete,
      Edit,
      Plus,
      Close,
      size,
      small,
      queryForm,
      selectRef,
      ...methods,
      filterTableData,
      ...toRefs(staticData)
    }
}


})



</script>

<style scoped>
.demo-pagination-block + .demo-pagination-block {
margin-top: 10px;
}
.demo-pagination-block .demonstration {
margin-bottom: 16px;
}
</style>
<style scoped>
.app_content{
  
  margin-top: 30px;
  margin-left: 10px;
}
.mb8{
  margin-bottom: 10px;
}
</style>